import 'package:edu/constants/app_strings.dart';
import 'package:edu/pages/course/course_detail/course_detail_page_logic.dart';
import 'package:edu/pages/course/course_detail/video_player/course_video_player_widget.dart';
import 'package:edu/pages/course/course_detail/video_player/course_video_player_widget_logic.dart';
import 'package:edu/utils/account_info.dart';
import 'package:edu/utils/app_router.dart';
import 'package:edu/utils/app_theme.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

class CourseCatalog extends StatelessWidget {
  const CourseCatalog({super.key});

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      key: const PageStorageKey('catalog'),
      slivers: [
        SliverPadding(
          padding: const EdgeInsets.only(bottom: 20.0),
          sliver: _buildCourseCategoryUnits(context),
        ),
      ],
    );
  }

  Widget _buildCourseCategoryUnits(BuildContext context) {
    return Selector<CourseDetailPageLogic, bool>(
      selector: (context, logic) => logic.isContentEmpty,
      builder: (context, v, child) {
        if (v) {
          return const Center(child: Text('暂无此课程的课程目录'));
        }
        final logic = context.read<CourseDetailPageLogic>();
        final units = logic.categoryUnits; // 课程目录
        return SliverFixedExtentList(
          itemExtent: 48.0,
          delegate: SliverChildBuilderDelegate(childCount: units.length, (
            context,
            index,
          ) {
            final unit = units[index];
            if (unit.isChapter) {
              return _buildCourseChapterUnit(context, unit);
            } else {
              return _buildCourseVideoUnit(context, unit);
            }
          }),
        );
      },
    );
  }

  // 每个章节单元
  Widget _buildCourseChapterUnit(
    BuildContext context,
    CourseTableContentUnit unit,
  ) {
    final style = Theme.of(
      context,
    ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold);
    return ListTile(
      title: Row(
        children: [
          Expanded(
            child: Text(
              unit.title,
              style: style,
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }

  // 每个课时单元
  Widget _buildCourseVideoUnit(
    BuildContext context,
    CourseTableContentUnit unit,
  ) {
    return Selector<CourseDetailPageLogic, bool>(
      selector: (_, logic) => logic.isPurchased || logic.isMycourse,
      builder: (context, v, child) {
        final style = Theme.of(context).textTheme.titleSmall;
        final videoIconColor = unit.isFree || v
            ? style?.color
            : AppTheme.shared.greyColor;
        final title = unit.timeString != null
            ? '${unit.title} ${unit.timeString}'
            : unit.title;

        return ListTile(
          onTap: unit.isFree || v
              ? () {
                  if (v) {
                    // 跳转视频播放页面
                    if (AccountInfo.shared.isLoggedIn == false) {
                      context.pushNamed(AppRouter.kLogin);
                      return;
                    }
                    final logic = context.read<CourseDetailPageLogic>();
                    if (logic.categoryUnits.length > 2) {
                      final unit = logic.categoryUnits[1];
                      showDialog(
                        context: context,
                        builder: (_) {
                          return ChangeNotifierProvider(
                            create: (_) =>
                                CourseVideoPlayerWidgetLogic(id: unit.id),
                            child: const CourseVideoPlayerWidget(),
                          );
                        },
                      );
                    }
                  } else {
                    // 提示请先购买课程
                  }
                }
              : null,
          title: Column(
            children: [
              const SizedBox(height: 8),
              Row(
                children: [
                  Icon(
                    Icons.play_circle_outline,
                    size: 20,
                    color: videoIconColor,
                  ),
                  const SizedBox(width: 10),
                  Expanded(
                    child: Text(
                      title,
                      style: style,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  if (unit.isFree && !v) const SizedBox(width: 10),
                  if (unit.isFree && !v)
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 4,
                        vertical: 2,
                      ),
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: AppTheme.shared.commonTipColor,
                          width: 1,
                        ),
                      ),
                      child: Text(
                        AppStrings.freeWatch,
                        style: TextStyle(
                          color: AppTheme.shared.commonTipColor,
                          fontSize: 10,
                        ),
                      ),
                    ),
                ],
              ),
              const SizedBox(height: 11),
              Divider(
                indent: 30,
                height: 1,
                thickness: 0.5,
                color: AppTheme.shared.greyColor,
              ),
            ],
          ),
        );
      },
    );
  }
}
